<template>
    <l-layout class="l-tab-page" :top="queryHeight + 12">
      <template #top>
        <l-panel style="padding-bottom:0;">
           <l-query 
            :labelWidth="100"
            :span="8"
            :items="queryItems" 
            :height.sync="queryHeight" 
            :formData="queryData" 
            :loading="loading" 
            @search="handleSearch">

             <template #f_Appler>
                <l-user-select v-model="queryData.f_Appler" ></l-user-select>
              </template>
              <template #f_ApplyDate >
                <l-date format="yyyy-MM-dd"  dateType="datetimerange" v-model="queryData.f_ApplyDate" :placeholder="$t('请选择')" >
                </l-date>
              </template>
              <template #f_PurchaseNo>
                <el-input v-model="queryData.f_PurchaseNo" :placeholder="$t('请输入')"></el-input>
              </template>
              <template #f_Theme>
                <el-input v-model="queryData.f_Theme" :placeholder="$t('请输入')"></el-input>
              </template>
              <template #f_PurchaseType >
                  <l-select   labelKey="f_ItemName" valueKey="f_ItemValue" :options="lr_dataItem['purchaseType']" v-model="queryData.f_PurchaseType" ></l-select>
              </template>
             
            </l-query>
        </l-panel>
      </template>

      <l-panel style="padding-top:4px;">
          <template #toolRight >
              <l-tool-btns  @click="handleAdd()"  :hasTableSetting="true" @setting="handleSetting">
              </l-tool-btns>
          </template>
          <l-table ref="mainTable" 
              :loading="tableLoading" 
              :columns="lr_getPageColumns(columns)" 
              :dataSource="tableData"
              :isPage="true"
              :pageTotal="tableTotal"
              :tablePage.sync="tableCurrentPage"
              @loadPageData="turnTablePage"
              >
              <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
          </l-table>
      </l-panel>

        <!--表单-->
        <l-dialog :title="$t(formTitle)"
                  :visible.sync="formVisible"
                  :height="600"
                  :width="1024"
                  @ok="handleSave"
                  @close="handleCloseForm"
                  @opened="handleOpenedForm">
            <my-form ref="form" ></my-form>
        </l-dialog>
        
    </l-layout>
</template>

<script>
// 这里借用采购入库的数据表格与表单
const api = window.$api.erp.warehousing
import MyForm from './form'
export default {
    components: {
        MyForm
    },
    data() {
        return {

            // 查询参数
            queryData:{
                f_Appler:'',
                f_PurchaseNo:'',
                f_ApplyDate:'',
                f_Theme:'',
                f_PurchaseType:'',
            },

            queryItems:[
                {label:'申请人',prop:'f_Appler'},
                {label:'单据编码',prop:'f_PurchaseNo'},
                {label:'申请日期',prop:'f_ApplyDate',},
                {label:'主题',prop:'f_Theme'},
                {label:'采购类别',prop:'f_PurchaseType'},
            ],
            loading:false,

            // 表格参数
            tableLoading: false,
            tableData:[],
            tableTotal:0,
            tableCurrentPage:1,
            tablePageSize:50,
            columns: [
                {label:'单据编码',prop:'f_PurchaseNo',minWidth:100,align:'left',isNotAutoWrap:true,},
                {label:'申请日期',prop:'f_ApplyDate',minWidth:160,align:'left',dataType:'datetime',},
                {label:'主题',prop:'f_Theme',minWidth:100,align:'left',isNotAutoWrap:true,},
                {label:'采购类别',prop:'f_PurchaseType',minWidth:100,align:'left',dataType:'mydata',options:[ {"value":"2","label":"新闻类"},{"value":"3","label":"产品类"},{"value":"4","label":"信息类"}]},
                {label:'申请人',prop:'f_Appler',width:80,align:'left',dataType:'user'},
                {label:'采购员',prop:'f_Purchaser',width:70,align:'left',dataType:'user'},
                {label:'申请单位',prop:'f_Department',width:120,align:'left',dataType:'company',isNotAutoWrap:true,},
                {label:'总价(元)',prop:'f_Total',minWidth:100,align:'left',isNotAutoWrap:true,},
                {label:'支付方式',prop:'f_PaymentType',minWidth:100,align:'left',dataType:'mydata',options:[{"value":"0","label":"现金"},{"value":"1","label":"票汇"},{"label":"信汇","value":"2"},{"label":"电汇","value":"3"},{"label":"承兑","value":"4"},{"label":"信用证","value":"5"}]},
                {label:'交货日期',prop:'f_DeliveryDate',minWidth:160,align:'left',dataType:'datetime',},
                {label:'点收人',prop:'f_PurchaseWarehousinger',minWidth:70,align:'left',dataType:'user'},
                {label:'点收日期',prop:'f_PurchaseWarehousingDate',minWidth:160,align:'left',dataType:'datetime',},
                {label:'对方代表',prop:'f_Your',minWidth:80,align:'left',isNotAutoWrap:true,},
                {label:'备注',prop:'f_Description',minWidth:180,align:'left',isNotAutoWrap:true},
            ],
            tableBtns:[
                {prop:'Edit',label:'编辑'},
                {prop:'Delete',label:'删除'},
            ],

            queryHeight:44,

            // 表单参数
            formVisible:false,
            formTitle:'',
            formEditRow:null,
            formEdit:false,
        };
    },
    computed: {},
    mounted() {
        this.init()
    },
    methods: {
        init() {
            this.loadTableData()
        },
         handleSetting(){
            this.$refs.mainTable.openColumnsSetting();
        },
        handleSearch(){
            this.loadTableData()
        },
        turnTablePage({rows}){
            this.tablePageSize = rows
            this.loadTableData(true)
        },
        async loadTableData(isNotFirst){
            if(!isNotFirst){
                this.tableCurrentPage = 1
            }
            this.tableLoading = true
            let queryData = this.$deepClone(this.queryData)
            if(!this.$validatenull(queryData.f_ApplyDate)){
                queryData.f_ApplyDate_end = queryData.f_ApplyDate.split(' - ')[1]
                queryData.f_ApplyDate = queryData.f_ApplyDate.split(' - ')[0]
            }

            queryData.rows = this.tablePageSize
            queryData.page = this.tableCurrentPage
            queryData.sidx = 'f_PurchaseType'
            let data = await this.$awaitWraper(api.getPage(queryData))
            if(data != null){
                this.tableData = data.rows
                this.tableTotal = data.records
            }
            else{
                this.tableData = []
            }
            this.tableLoading = false
        },

        handleAdd(){
            this.formEdit = false
            this.handleShowForm("新增入库")
        },
        handleEdit($index,row){
            this.formEdit = true
            this.formEditRow = row
            this.handleShowForm("编辑入库")
        },
        handleDelete($index,row){
            this.$confirm(this.$t('此操作将永久删除该数据, 是否继续?'), this.$t('提示'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
            }).then(async () => {
                this.tableData.splice($index,1);
                this.tableTotal--;
                await api.remove(row.f_Id)
                this.$message({
                    type: 'success',
                    message: this.$t('删除成功!')
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已取消删除!')
                })
            })
        },

        async handleSave(showLoading, hideLoading) {
            if (await this.$refs.form.validateForm()) {
                showLoading()
                const postData = this.$refs.form.getForm()
                let res = ''
                if(this.formEdit){// 编辑
                    res = await this.$awaitWraper(api.update(this.formEditRow.f_Id,postData))
                }
                else{// 新增
                    res = await this.$awaitWraper(api.add(postData))
                }
                if(res){
                    this.$message({
                        type: 'success',
                        message: this.$t('保存成功!')
                    })
                    this.loadTableData()
                    this.formVisible = false
                }

                hideLoading()
            }
        },

        handleShowForm(text) {
            this.formTitle = text;
            this.formVisible = true;
        },
        async handleOpenedForm(showLoading, hideLoading) {
            if (this.formEdit) {
                showLoading('加载数据中...')
                let data = await this.$awaitWraper(api.get(this.formEditRow.f_Id))
                if(data){
                    this.$refs.form.setForm(data)
                }
                hideLoading()
            }
        },
        handleCloseForm() {
            this.$refs.form.resetForm();
        },



    flitterData (arr) {
      let spanOneArr = []
      let concatOne = 0
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1)
        } else {
          if (item.f_PurchaseType === arr[index - 1].f_PurchaseType) { //第一列需合并相同内容的判断条件
            spanOneArr[concatOne] += 1
            spanOneArr.push(0)
            
          } else {
            spanOneArr.push(1)
            concatOne = index
          }
        }
      })
      return {
        one: spanOneArr,
      }
    },
    arraySpanMethod({ row, rowIndex, columnIndex }) {
        if( columnIndex === 5){
            if(row.f_Appler==row.f_Purchaser){
                return [1,2]
            }
            
        }else if(columnIndex === 6){
            if(row.f_Appler==row.f_Purchaser){
                return [0,2]
            }
        }

        if (columnIndex === 4) {  // 判断哪一列
        const _row = (this.flitterData(this.tableData).one)[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        };
      }

    }
}
}
</script>


